import request from './axios'

export const studyApi = {
  // 获取学习记录列表
  getStudyRecords(params = {}) {
    const userId = localStorage.getItem('userId')
    return request({
      url: '/study/records/',
      method: 'get',
      params: {
        ...params,
        user_id: userId // 始终添加当前用户ID
      }
    })
  },

  // 创建学习记录
  createStudyRecord(data) {
    return request({
      url: '/study/records/',
      method: 'post',
      data
    })
  },

  // 删除学习记录
  deleteStudyRecord(id) {
    return request({
      url: `/study/records/${id}/`,
      method: 'delete'
    })
  },

  // 获取学习统计
  getStatistics() {
    return request({
      url: '/study/statistics/',
      method: 'get'
    })
  },

  // 保存学习记录
  saveStudyRecord(data) {
    const userId = localStorage.getItem('userId')
    if (!userId) {
      return Promise.reject(new Error('请先登录'))
    }
    return request({
      url: '/study/records/',
      method: 'post',
      data: {
        ...data,
        user: parseInt(userId),  // 使用 user 而不是 user_id
        user_id: parseInt(userId)  // 保留 user_id 用于后端处理
      }
    })
  },

  // 获取评论列表
  getComments(recordId) {
    return request({
      url: `/study/records/${recordId}/comments/`,
      method: 'get'
    })
  },

  // 添加评论
  addComment(recordId, content) {
    const userId = localStorage.getItem('userId')
    return request({
      url: `/study/records/${recordId}/comments/`,
      method: 'post',
      data: {
        user_id: parseInt(userId),
        content
      }
    })
  },

  // 点赞/取消点赞
  toggleStar(recordId) {
    const userId = localStorage.getItem('userId')
    return request({
      url: `/study/records/${recordId}/star/`,
      method: 'post',
      data: {
        user_id: parseInt(userId)
      }
    })
  }
}
